import React, { useEffect } from 'react';
import { ArrowLeft } from '@nutui/icons-react';
import './MapPage.css';
import AMapLoader from '@amap/amap-jsapi-loader';

export default function MyRentalHousing() {
  useEffect(() => {
    AMapLoader.load({
      key: '8be2bfb5fa90730e0385e612261c8de5',
      version: '2.0',
      plugins: ['AMap.Geolocation', 'AMap.Geocoder','PlaceSearch']
    }).then((AMap) => {
      const map = new AMap.Map('container', {
        zoom: 10,
        center: [116.397428, 39.90923]
      });

      AMap.plugin('AMap.Geolocation', function () {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 5000,
          offset: [10, 20],
          zoomToAccuracy: true,
          position: 'RB',
          maximumAge: 0
        });

        geolocation.getCurrentPosition(function (status, result) {
          console.log(status, result);
          if (status === 'complete') {
            const position = result.position;
            // 根据定位精度动态调整地图缩放级别
            let zoomLevel = result.accuracy > 100? 10 : result.accuracy > 50? 12 : result.accuracy > 20? 14 : result.accuracy > 10? 16 : 18;
            map.setZoomAndCenter(zoomLevel, position);

            // 使用地理编码服务将经纬度转换为地址信息
            const geocoder = new AMap.Geocoder({
              city: result.regeocode?.addressComponent?.city || "全国"
            });
            geocoder.getAddress(position, function(status, result) {
              if (status === 'complete' && result.regeocode) {
                console.log(result.regeocode.formattedAddress);
                // 从地址信息中提取小区名称（这里只是一个简单示例，实际可能需要更复杂的处理）
                const addressComponents = result.regeocode.addressComponent;
                const neighborhood = addressComponents.neighborhood || addressComponents.building || addressComponents.streetNumber || '未知小区';
                console.log('小区名称：', neighborhood);
              } else {
                console.error('地理编码失败：', status);
              }
            });
          } else {
            console.log(result.info);
          }
        });
      });

    }).catch((error) => {
      console.error(error);
    });

  }, []);

  return (
    <div className='MapPage'>
      <div className='MapPage_top'>
        <ArrowLeft className="back-icon" width={"40px"} onClick={() => window.history.back()} />
        <span className="title-text">高德地图</span>
      </div>
      <div id="container" style={{ height: '100%' }}></div>
    </div>
  );
}